package com.zxu.test.util;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;

import java.lang.reflect.Field;
import java.lang.reflect.Method;


/**
 * Class to manage status and navigation bar tint effects when using KitKat
 * translucent system UI modes.
 */
public class SystemBarManager {

	public static void set(Activity activity) {
		StatusBarLightMode(activity);
	}

	public static void setTopState(Activity activity, View view) {
		if (activity == null) {
			return;
		}

		//当系统版本为4.4或者4.4以上时可以使用沉浸式状态栏
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			//透明状态栏
			activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			//透明导航栏
//			activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

			if (view != null) {
				if (view.getBackground() instanceof ColorDrawable && ((ColorDrawable) view.getBackground()).getColor() == Color.WHITE) {
					SystemBarManager.set(activity);
				}

				view.setVisibility(View.VISIBLE);
				int statusHeight = getStatusBarHeight(activity);

				ViewGroup.LayoutParams params = view.getLayoutParams();
				params.height = statusHeight;
				view.setLayoutParams(params);

			} else {
				SystemBarManager.set(activity);
			}

		} else {
			if (view != null) {
				view.setVisibility(View.GONE);
			}
		}

	}

	public static void setTopState(Activity activity, View view, int color) {
		if (activity == null) {
			return;
		}

		//当系统版本为4.4或者4.4以上时可以使用沉浸式状态栏
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			//透明状态栏
			activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			//透明导航栏
//			activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

			if (view != null) {
				view.setVisibility(View.VISIBLE);
				view.setBackgroundResource(color);

				int statusHeight = getStatusBarHeight(activity);

				ViewGroup.LayoutParams params = view.getLayoutParams();
				params.height = statusHeight;
				view.setLayoutParams(params);
			}
		}

	}

	//Get status bar height
	public static int getStatusBarHeight(Context context) {
		int result;
		int resId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
		if (resId > 0) {
			result = context.getResources().getDimensionPixelOffset(resId);
		} else {
			result = DisplayUtils.dp2px(context, 20);
		}

		return result;
	}

	/**
	 * 设置状态栏黑色字体图标，
	 * 适配4.4以上版本MIUIV、Flyme和6.0以上版本其他Android
	 *
	 * @param activity
	 * @return 1:MIUUI 2:Flyme 3:android6.0
	 */
	public static int StatusBarLightMode(Activity activity) {
		int result = 0;
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			if (Rom.isMIUI9()) {//MUUI9适配
				result = 5;
			} else if (MIUISetStatusBarLightMode(activity.getWindow(), false)) {
				result = 1;
			} else if (FlymeSetStatusBarLightMode(activity.getWindow(), false)) {
				result = 2;
			} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
				activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
				result = 3;
			} else {
				result = 4;
			}
		}

		StatusBarLightMode(activity, result);
		return result;
	}

    /**
     * 设置状态栏黑色字体图标，
     * 适配4.4以上版本MIUIV、Flyme和6.0以上版本其他Android
     *
     * @param activity
     * @return 1:MIUUI 2:Flyme 3:android6.0
     */
    public static int statusBarDarkMode(Activity activity) {
        int result = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Rom.isMIUI9()) {//MUUI9适配
                result = 5;
            } else if (MIUISetStatusBarLightMode(activity.getWindow(), true)) {
                result = 1;
            } else if (FlymeSetStatusBarLightMode(activity.getWindow(), true)) {
                result = 2;
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
                result = 3;
            } else {
                result = 4;
            }
        }

        StatusBarLightMode(activity, result);
        return result;
    }

	/**
	 * 已知系统类型时，设置状态栏黑色字体图标。
	 * 适配4.4以上版本MIUIV、Flyme和6.0以上版本其他Android
	 *
	 * @param activity
	 * @param type     1:MIUUI 2:Flyme 3:android6.0
	 */
	public static void StatusBarLightMode(Activity activity, int type) {
		if (type == 1) {
			MIUISetStatusBarLightMode(activity.getWindow(), true);
		} else if (type == 2) {
			FlymeSetStatusBarLightMode(activity.getWindow(), true);
		} else if (type == 3 || type == 5) {
			activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
		} else if (type == 4) {
			setTranslucentForCoordinatorLayout(activity, 70);
		}
	}

    /**
     * 已知系统类型时，设置状态栏黑色字体图标。
     * 适配4.4以上版本MIUIV、Flyme和6.0以上版本其他Android
     *
     * @param activity
     * @param type     1:MIUUI 2:Flyme 3:android6.0
     */
    public static void StatusBarDarkMode(Activity activity, int type) {
        if (type == 1) {
            MIUISetStatusBarLightMode(activity.getWindow(), false);
        } else if (type == 2) {
            FlymeSetStatusBarLightMode(activity.getWindow(), false);
        } else if (type == 3 || type == 5) {
            activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else if (type == 4) {
            setTranslucentForCoordinatorLayout(activity, 70);
        }
    }

	//带有透明颜色的状态栏
	public static void setTranslucentForCoordinatorLayout(Activity activity, int statusBarAlpha) {
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
			return;
		}

		transparentStatusBar(activity);//先将状态栏设置为完全透明
		addTranslucentView(activity, statusBarAlpha);//添加一个自定义透明度的矩形状态栏
	}

	/**
	 * 使状态栏透明
	 */
	@TargetApi(Build.VERSION_CODES.KITKAT)
	private static void transparentStatusBar(Activity activity) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
			activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
		} else {
			activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		}
	}

	/**
	 * 添加半透明矩形条
	 *
	 * @param activity       需要设置的 activity
	 * @param statusBarAlpha 透明值
	 */
	private static void addTranslucentView(Activity activity, int statusBarAlpha) {
		ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content);
		if (contentView.getChildCount() > 1) {
			contentView.getChildAt(1).setBackgroundColor(Color.argb(statusBarAlpha, 0, 0, 0));
		} else {
			contentView.addView(createTranslucentStatusBarView(activity, statusBarAlpha));
		}
	}

	/**
	 * 创建半透明矩形 View
	 *
	 * @param alpha 透明值
	 * @return 半透明 View
	 */
	private static View createTranslucentStatusBarView(Activity activity, int alpha) {
		// 绘制一个和状态栏一样高的矩形
		View statusBarView = new View(activity);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(activity));
		statusBarView.setLayoutParams(params);
		statusBarView.setBackgroundColor(Color.argb(alpha, 0, 0, 0));
		return statusBarView;
	}

	/**
	 * 清除MIUI或flyme或6.0以上版本状态栏黑色字体
	 */
	public static void statusBarDarkMode(Activity activity, int type) {
		if (type == 1) {
			MIUISetStatusBarLightMode(activity.getWindow(), false);
		} else if (type == 2) {
			FlymeSetStatusBarLightMode(activity.getWindow(), false);
		} else if (type == 3) {
			activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
		}

	}

	/**
	 * 设置状态栏字体图标为深色，需要MIUIV6以上
	 *
	 * @param window 需要设置的窗口
	 * @param dark   是否把状态栏字体及图标颜色设置为深色
	 * @return boolean 成功执行返回true
	 */
	public static boolean MIUISetStatusBarLightMode(Window window, boolean dark) {
		boolean result = false;
		if (window != null) {
			Class clazz = window.getClass();
			try {
				int darkModeFlag = 0;
				Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
				Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
				darkModeFlag = field.getInt(layoutParams);
				Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
				if (dark) {
					extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
				} else {
					extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
				}
				result = true;
			} catch (Exception e) {

			}
		}
		return result;
	}

	/**
	 * 设置状态栏图标为深色和魅族特定的文字风格，Flyme4.0以上
	 * 可以用来判断是否为Flyme用户
	 *
	 * @param window 需要设置的窗口
	 * @param dark   是否把状态栏字体及图标颜色设置为深色
	 * @return boolean 成功执行返回true
	 */
	public static boolean FlymeSetStatusBarLightMode(Window window, boolean dark) {
		boolean result = false;
		if (window != null) {
			try {
				WindowManager.LayoutParams lp = window.getAttributes();
				Field darkFlag = WindowManager.LayoutParams.class
						.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
				Field meizuFlags = WindowManager.LayoutParams.class
						.getDeclaredField("meizuFlags");
				darkFlag.setAccessible(true);
				meizuFlags.setAccessible(true);
				int bit = darkFlag.getInt(null);
				int value = meizuFlags.getInt(lp);
				if (dark) {
					value |= bit;
				} else {
					value &= ~bit;
				}
				meizuFlags.setInt(lp, value);
				window.setAttributes(lp);
				result = true;
			} catch (Exception e) {

			}
		}
		return result;
	}

}